<?php
    @session_start();
    require_once 'shared-functions.php';
    require_once 'session.php';
    require_once 'masterpage.php';
    
    if(!IsValidSession())
    {
        header('Location: login.php?page=view-log');
        exit();
    }
    else
    {
    	RefreshSession();
    }
	
	$user = GetCurrentUserAccessLevel();
	
    //Check user access
    if($user != $DIRECTOR && $user != $ADMIN)
    {
        header('Location: login.php?page=view-log&error=To access the view log page, please log in as a director or admin&logout=1');
        exit();
    }

    masterpage("View Log");
	
	if(isset($_POST['datepicker1']) && isset($_POST['datepicker2']))
	{
		$datepicker1 = $_POST["datepicker1"];	
		$datepicker2 = $_POST["datepicker2"];
	}
	else
	{
		// Default to search through past week's logs
		$datepicker1 = date('d-m-Y', strtotime('-7 days')); // Start date to search for
		$datepicker2 = date('d-m-Y'); // End date to search for
	}
	
	echo "<form action='view-log.php' method='POST'>";
	echo "<input type='hidden' name='isSubmitted' value='true'/>";
	echo "<strong>View logs</strong><br/>";
	echo "<input type='radio' name='datespan' value='spanrange' checked='checked'/> from earliest date: <input type='text' id='datepicker1' name='datepicker1' value='$datepicker1'/>";
	echo "&nbsp;&nbsp;to latest date: <input type='text' id='datepicker2' name='datepicker2' value='$datepicker2'/>";
	echo "<br/>";
	echo "<input type='radio' name='datespan' value='alldates' /> all dates";
	echo "<br/>";
	echo "User: ";
	echo "<select name='UserID'>";
	echo "<option value='-1'>All</option>";
	$link = connect_db();
	$query = "SELECT `UserId`, `FirstName`, `MiddleName`, `LastName` FROM `User` WHERE `Active` = '1' AND `PrivilegeLevel` != '1'";
	$users = mysql_query($query,$link);
	if(!$users)
	{
		echo "Oops...something went wrong. Please contact support.";
        exit();
	}
	while($userrow = mysql_fetch_array($users,MYSQL_BOTH))
	{
		echo "<option value='".$userrow['UserId']."'>".$userrow['FirstName']." ".$userrow['LastName']." - ".$userrow['UserId']."</option>";
	}
	echo "</select>";
	echo "<br/><br/>";
	echo "<input type='submit' value='Update View'/>";
	echo "</form>";
	
	// Convert from dd-mm-yyyy format to yyyy-mm-dd for comparing with the database
	$d1Day = substr($datepicker1, 0, 2);
	$d1Month = substr($datepicker1, 3, 2);
	$d1Year = substr($datepicker1, 6, 4);
	
	$d2Day = substr($datepicker2, 0, 2);
	$d2Month = substr($datepicker2, 3, 2);
	$d2Year = substr($datepicker2, 6, 4);
	
	// Format the date for the sql query below. Times added for accurate search results, to include the whole day regardless of time.
	$formattedDate1 = $d1Year."-".$d1Month."-".$d1Day." 00:00:00";
	$formattedDate2 = $d2Year."-".$d2Month."-".$d2Day." 23:59:59";

    //$link = connect_db();
    $query = "SELECT `Time`, `Table`, `ChangeDescription`, `Log`.`UserId`, `FirstName`, `MiddleName`, `LastName`";
	$query .= " FROM `Log` INNER JOIN `User` ON `Log`.`UserId` = `User`.`UserId`";
	$query .= " WHERE `Log`.`UserId` is not null"; // Added this always true 'WHERE' line to make all possible subsequent 'WHERE' lines start with 'AND'
	
	// if getting to the page first time (not submitted form) default to show logs for the date range from the datepickers, which default to previous 1 week
	if(!isset($_POST['isSubmitted']) || 
		(isset($_POST['datespan']) && $_POST['datespan'] == 'spanrange'))
	{
		$query .= " AND `Time` >= '$formattedDate1'";
		$query .= " AND `Time` <= '$formattedDate2'";
	}
	
	if(isset($_POST['UserID']) && $_POST['UserID'] != '-1')
	{
		$query .= " AND `Log`.`UserId` = '".$_POST['UserID']."'";
	}
	
    $logs = mysql_query($query,$link);
    if(!$logs)
    {
        echo "Oops...something went wrong. Please contact support.";
        exit();
    }
	
	echo "<br/>";
    echo "<table class='DataList'>";
    echo "  <thead>";
    echo "    <tr><th class='header'>Time</th><th class='header'>Table</th><th class='header'>User</th><th class='header'>Change Description</th></tr>";
    echo "  </thead>";
    echo "  <tbody>";

	$rowID = 0;
    while($tblrow = mysql_fetch_array($logs,MYSQL_BOTH))
    {
	  if ($rowID == 0)
	  {
		$rowClass = "rows";
		$rowID++;
	  }
	  else
	  {
		$rowClass = "altrows";
		$rowID--;
	  }
	  echo "<tr class='$rowClass'>";
	  echo "<td>".date('d-m-Y H:i:s', strtotime($tblrow['Time']))."</td>";
	  echo "<td>".$tblrow['Table']."</td>";
	  echo "<td>".$tblrow['FirstName']." ".$tblrow['LastName']." - ".$tblrow['UserId']."</td>";
	  echo "<td>".$tblrow['ChangeDescription']."</td></tr>";
    }

    echo '  </tbody>';
    echo '</table>';
?>

<!-- Javascript copied from add-new-semester for datepicker controls -->
<link type="text/css" href="jquery/css/overcast/jquery-ui-1.8.9.custom.css" rel="stylesheet" />	
	<script type="text/javascript" src="jquery/js/jquery-1.4.4.min.js"></script>
	<script type="text/javascript" src="jquery/js/jquery-ui-1.8.9.custom.min.js"></script>
	<script type="text/javascript">
		$(function(){

			// Dialog			
			$('#dialog').dialog({
				autoOpen: false,
				width: 600,
				buttons: {
					"Ok": function() { 
						$(this).dialog("close"); 
					}, 
					"Cancel": function() { 
						$(this).dialog("close"); 
					} 
				}
			});
		
			// Dialog Link
			$('#dialog_link').click(function(){
				$('#dialog').dialog('open');
				return false;
			});

			// Datepicker1
			$('#datepicker1').datepicker({
				dateFormat: 'dd-mm-yy',
				width: '100px',
				inline: true
			});

			// Datepicker2
			$('#datepicker2').datepicker({
				dateFormat: 'dd-mm-yy',
				inline: true
			});
		
			//hover states on the static widgets
			$('#dialog_link, ul#icons li').hover(
				function() { $(this).addClass('ui-state-hover'); }, 
				function() { $(this).removeClass('ui-state-hover'); }
			);
		
		});
	</script>
	<script type="text/javascript">
		$(document).ready(function() {
			// Onload function
		});
		
	</script>
	<style type="text/css">
		div.ui-datepicker{ font-size:12px;}
	</style>

<?php
    endmasterpage();
?>

